import click
from flask.cli import AppGroup
from app.models.user import User
from app.models.role import Role
from app.extensions import db
import requests
import random


def register_cli(app):
    init_cli = AppGroup('init', short_help='初始化工作')
    app.cli.add_command(init_cli)

    @init_cli.command(short_help='生成管理员')
    @click.option('--username', default='admin', help='账号')
    @click.option('--password', default='123456', help='密码')
    def admin(username, password):
        if not Role.query.first():
            print('初始化角色')
            Role.init_role()

        if User.query.filter_by(username=username).first():
            raise '账号已经生成，不需要重复生成！'

        user = User(username=username, password=password, nickname='江先生')
        db.session.add(user)
        db.session.commit()
        click.echo('成功生成账号:{}, 密码:{}'.format(username, password))

    @init_cli.command(short_help='重置密码')
    @click.option('--username', help='账号')
    @click.option('--password', help='密码')
    def reset_password(username, password):
        user = User.query.filter(User.username == username).first()
        with db.auto_commit():
            user.password = password

        click.echo('账户密码重置成功')

    @init_cli.command(short_help='获取账单')
    def get_bills():
        url = 'https://wx.tenpay.com/userroll/userrolllist?classify_type=0&count=20&csrf_token=on%2Bn%2BDyXnEvGAVCQQoYFw72evY85KlZg&exportkey=AfHnAiVwdYnPyXN9qAvqjEQ%3D&sort_type=1'
        cookies = {
            "userroll_encryption": "CmypDodM8BJbGsYcUKGP1Ta0aoiFKcFjZsXX46zvVLD2PjPf/7cfV+y1650oUoLSeTXX83EmY3cMIowezDw99ksvZL1zAWPh/ZPv9tdTLEfMCRav7WvdSYvIzOAChTlT4TcNhFPSIQHPbuUv+rr38w==",
            "userroll_pass_ticket": "DTWKtBGBL/3B+VxRhNZCD55p/cM4jLFa/uCo8q9MIgWEJptEz6cfyXvnuEy1QaXt", 
            "userroll_version" : "1", 
            "wxp_log_uid": "BgAAy%2FUNeSWDxHPPisTWRIVOhxBAwztJu7ZzKY4%3D"
        }
        # bills.delay(url, cookies)
        click.echo('账单获取成功')